/*
 * Copyright (c) 2021
 * User:魔金多商户商城
 * File:WxgzhUtil.java
 * Date:2021/01/13 20:43:13
 */

package com.ruoyi.common.utils;


import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.bean.Template;
import com.ruoyi.common.utils.bean.TemplateParam;
import com.ruoyi.common.utils.bean.WechatSetting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class WxgzhUtil {
    @Autowired
    private static final Logger log = LoggerFactory.getLogger(WxgzhUtil.class);


    /**
     * http请求方法
     *
     * @param requestUrl
     * @param requestMethod
     * @param outputStr
     * @return
     */
    public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        try {
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            if (outputStr != null) {
                OutputStream outputStream = conn.getOutputStream();

                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            conn.disconnect();
            return buffer.toString();
        } catch (ConnectException ce) {
            System.out.println("连接超时：{}");
        } catch (Exception e) {
            System.out.println("https请求异常：{}");
        }
        return null;
    }

    /**
     * 发送模板消息
     *
     * @param template
     * @return
     */
    public static boolean sendTemplateMsg(Template template, WechatSetting wechatSetting) {
        boolean flag = false;
        String accessToken = WeChatAppletUtils.getAccessToken(wechatSetting);
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken);
        String Result = httpsRequest(requestUrl, "POST", template.toJSON());

        JSONObject jsonResult = JSONObject.parseObject(Result);
        if (jsonResult != null) {
            int errorCode = jsonResult.getIntValue("errcode");
            String errorMessage = jsonResult.getString("errmsg");
            if (errorCode == 0) {
                flag = true;
            } else {
                System.out.println("模板消息发送失败:" + errorCode + "," + errorMessage);
            }
        }
        return flag;
    }

    //  测试
    public static void main(String[] args) {
        WechatSetting wechatSetting = new WechatSetting();
        wechatSetting.setAppId("wx6007249d6b2348ea");
        wechatSetting.setAppSecret("1b1c5e732f38a03c980061855e68a19a");
        Template template = new Template();
        //这里填写模板ID
        template.setTemplate_id("fEmOiKAqvm_fkbLq8ryC8q3cjJAH0R2blnXHUNmUy8I");
        //这里填写用户的openid
        template.setTouser("oQGdI4-CspJm_GJ-bZiTyT64f9tE");
        //这里填写点击订阅消息后跳转小程序的界面
        template.setPage("pages/progress/progressList");
        List<TemplateParam> paras = new ArrayList<>();
        paras.add(new TemplateParam("car_number1", "川AED606"));
        paras.add(new TemplateParam("thing2", "维修完成"));
        paras.add(new TemplateParam("date3", "2019-12-18 09:23:09"));
        paras.add(new TemplateParam("thing4", "测试订阅号"));
        template.setTemplateParamList(paras);
        sendTemplateMsg(template, wechatSetting);
    }


}